package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 *
 * @Title: aipHSTActivityVerify
 * @Description:华盛证券 名单下发 重新查询客户 是否涉及活动，如涉及则写入对应的活动详情博鳌 --内部接口
 * @author: chieh
 * @date 2022-04-06 13:00:00
 *
 */

public class aipHSTActivityVerify implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTActivityVerify.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def hst_no = inObject.getString("hst_no");//华盛号
            def register_id = inObject.getString("register_id");//注册渠道id

            log.debug("解析信息-" + "hst_no: " + hst_no + "	register_id: " + register_id);
            if (hst_no!=""&&hst_no!=null&register_id!=""&&register_id!=null) {
                outData = allocationData(eliteBean,hst_no,register_id,dataSourceID);
            }else{
				log.error("处理失败(字段为空错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"1\",\"resultmessage\":\"处理失败(字段为空错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
			}

        } catch (Exception e) {
            log.error("活动复查绑定接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("活动复查绑定返回结果:" + outData);

        return outData;
    }

    // 处理开发名单任务
    public static String allocationData(EliteBean eliteBean,String hst_no,String register_id,String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

       try {

			//1.根据渠道号 查询客户渠道对应的活动-且在有效期时间内的活动
			def selectactivitybatchSQL = "select a1.batchid as batchid,a1.tab_activity_id as tab_activity_id FROM hst_activity_batch a1 left join hst_channel_relation a2 on a2.rule_id=a1.rec_guid and  type='activity' left join hst_Activity a3 on a3.tab_activity_id=a1.tab_activity_id where 1=1 and a2.code_id='" + register_id + "'  and tab_activity_starttime< NOW() and  tab_activity_endtime> NOW()";
			log.debug("查询分配数量selectactivitybatchSQL="+selectactivitybatchSQL);

			List selectactivitybatchList = eliteBean.chaxun_sql(selectactivitybatchSQL, "dataSource");
			def selectactivitybatchNum = selectactivitybatchList.size();
			log.debug("selectactivitybatch ListNum=" + selectactivitybatchNum);
            //涉及活动则循环写入
           if(selectactivitybatchNum>0){
               for (int i = 0; i < selectactivitybatchNum; i++) {
                   Map selectactivitybatchSQLMap = selectactivitybatchList.get(i);

                   def batchid = selectactivitybatchSQLMap.get("batchid");//批次号
                   def tab_activity_id = selectactivitybatchSQLMap.get("tab_activity_id");//活动id

                   def getSelectactivitySQL = eliteBean.chaxun_sql("select a.hst_no  FROM hst_activity_batch a1 left join hst_activity_batch_list a on a.batchid=a1.batchid where 1=1 and a.hst_no='" + hst_no + "' and a1.batchid='" + batchid + "'", "dataSource");
                   log.debug("查询当前名单，涉及活动 SQL:" + getSelectactivitySQL + " 结果数量:" + getSelectactivitySQL.size());

                   //没有则新增 有则不动
                   if(getSelectactivitySQL.size() == 0) {
					   //活动list
					   String updateactivity_batch_listSQL = "INSERT INTO hst_activity_batch_list(rec_id, batchid, hst_no, result_code, result_desc, customer_guid, objective_guid, import_time) SELECT uuid(),'" + batchid + "',c.customer_id,1,'活动复查绑定成功',o.customer_guid,o.OBJECTIVE_GUID,date_format(now(),'%Y-%m-%d %H:%i:%s') FROM objective o left join customer c on o.customer_guid=c.customer_guid where c.customer_id='" + hst_no + "' and o.map_id='MY48ZX'";
                       eliteBean.update(updateactivity_batch_listSQL, "dataSource");
					   
					   //记录活动的表
                       String updateactivitySQL = "INSERT INTO elitetask_activity(hst_no,batchid,tab_activity_id,customer_guid,objective_guid,Createdby,Createddate) SELECT '" + hst_no + "','" + batchid + "','" + tab_activity_id + "',o.customer_guid,o.OBJECTIVE_GUID,'SELITE',date_format(now(),'%Y-%m-%d %H:%i:%s') FROM objective o left join customer c on o.customer_guid=c.customer_guid where c.customer_id='" + hst_no + "' and o.map_id='MY48ZX'";
                       eliteBean.update(updateactivitySQL, "dataSource");
					   
					   
                   }else{
                       log.debug("查询当前名单，涉及活动,但都已参与，不做操作!");
                   }

               }
           }else{
               log.debug("查询当前名单，不涉及活动!");
           }

            // 生成处理完成时间
            endTime = System.currentTimeMillis();
			
            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", -1);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }
	
	// 解析Json值
		public static String GetJV(JSONObject inJson, String getKey) {
			String Rev_Value = null;
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e1) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
					} catch (Exception e2) {
						try {
							Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
						} catch (Exception e3) {
							Rev_Value = "";
						}
					}
				}
			} finally {
				if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
					Rev_Value = "";
				} else {
				}
			}
			log.debug("解析-k=" + getKey + " v=" + Rev_Value);
			return Rev_Value;
		}

}
